import React, { useRef, useState } from "react";
import { IMessage } from "./types";

import { v4 as uuidv4 } from 'uuid';

import './index.css'

function App() {
  const [messages, setMessages] = useState<IMessage[]>([]);
  const [body, setBody] = useState('');
  const socket = useRef<WebSocket>()
  const [connected, setConnected] = useState(false);
  const [username, setUsername] = useState('')

  function connect() {
    socket.current = new WebSocket('ws://localhost:8080')

    socket.current.onopen = () => {
      setConnected(true)
      const message = {
        event: 'connection',
        username,
        id: uuidv4()
      }
      socket.current?.send(JSON.stringify(message))
    }
    socket.current.onmessage = (event) => {
      const message = JSON.parse(event.data)
      setMessages(prev => [message, ...prev])
    }
    socket.current.onclose = () => {
      console.log('Socket закрыт')
    }
    socket.current.onerror = () => {
      console.log('Socket произошла ошибка')
    }
  }

  const sendMessage = async () => {
    const message = {
      username,
      body,
      id: uuidv4(),
      event: 'message'
    }
    socket.current?.send(JSON.stringify(message));
    setBody('')
  }

  if (!connected) {
    return (
      <div className="center">
        <div className="form">
          <input
            value={username}
            onChange={e => setUsername(e.target.value)}
            type="text"
            placeholder="Введите ваше имя" />
          <button onClick={connect}>Войти</button>
        </div>
      </div>
    )
  }


  return (
    <div className="center">
      <div>
        <div className="form">
          <input value={body} onChange={e => setBody(e.target.value)} type="text" />
          <button onClick={sendMessage}>Отправить</button>
        </div>
        <div className="messages">
          {messages.map(mess =>
            <div key={mess.id}>
              {mess.event === 'connection'
                ? <div className="connection_message">
                  Пользователь {mess.username} подключился
                </div>
                : <div className="message">
                  {mess.username}. {mess.body}
                </div>
              }
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

export default App;
